//
//  KSearchViewController.m
//  KCZ_B段项目
//
//  Created by dllo on 15/11/9.
//  Copyright © 2015年 Sky. All rights reserved.
//

#import "KSearchViewController.h"
#import "FitHeader.h"
#import "HTTPMethod.h"
#import "changeString.h"
#import "KSearchSuggestModel.h"
#import "KSearchPushVController.h"
#import <MBProgressHUD.h>
#import "FontSizeSingleTon.h"
#import "Loading.h"
#define FontSize [[FontSizeSingleTon shareFontSize]array]
@interface KSearchViewController ()<UISearchBarDelegate,UITableViewDataSource,UITableViewDelegate>
@property(nonatomic, strong)UISearchBar *searchBar;
@property(nonatomic, strong)NSString *searchString;
@property(nonatomic, strong)UITableView *tableView;
@property(nonatomic, strong)NSMutableArray *dataArray;
@property(nonatomic, strong)NSString *bodyString;
@property(nonatomic, strong)UIView *backView;
@property(nonatomic, strong)Loading *load;
@end

@implementation KSearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.translucent = NO;
    self.view.backgroundColor = [UIColor whiteColor];
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],NSForegroundColorAttributeName, nil]];
    
    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];//navigationcontroller上的颜色为白色
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(cancelAction)];
    _searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(80 * wt, 10 * ht,  215 * wt, 20 * ht)];
    _searchBar.delegate = self;
    self.navigationItem.titleView =  _searchBar;
    // Do any additional setup after loading the view.
}
-(void)loadView
{
    [super loadView];
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREENWIDTH, SCREENHEIGHT - 49)];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    [self creatViews];
    
}
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    if (![searchText isEqualToString:@""]) {
        _bodyString = [NSString stringWithFormat:@"methodName=SearchKeyword&keyword=%@&version=4.02",searchText];
        _searchString = [searchText copy];
        [_backView removeFromSuperview];
        NSMutableArray *array = [NSMutableArray array];
        for (NSInteger i = 0; i < 70; i++) {
            [array addObject:[NSString stringWithFormat:@"%ld", i + 1]];
        }
        _load = [[Loading alloc]initWithFrame:CGRectMake(0, 0, SCREENWIDTH, SCREENHEIGHT - 64 - 49) PicArray:array];
        [self.view addSubview:_load];
        [self getData];
    }
    else {
        [_dataArray removeAllObjects];
        [_tableView reloadData];
        [self creatViews];
    }
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [_searchBar resignFirstResponder];
    KSearchSuggestModel *model = [[KSearchSuggestModel alloc]init];
    model = _dataArray[indexPath.row];
    KSearchPushVController *kpvc = [[KSearchPushVController alloc]init];
    kpvc.searchString = model.text;
    [self.navigationController pushViewController:kpvc animated:YES];
}
-(void)creatViews
{
    _backView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREENWIDTH, SCREENHEIGHT - 49)];
    _backView.backgroundColor = [UIColor whiteColor];
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(100 * wt, 100 * ht, 215 * wt, 50 * ht)];
    label.text = @"输入关键词开始搜索吧~";
    label.textColor = [UIColor colorWithRed:0.19 green:0.75 blue:0.6 alpha:1];
    label.font = [UIFont systemFontOfSize:[FontSize[0] integerValue]];
    [_backView addSubview:label];
    [self.view addSubview:_backView];
}

-(void)getData
{
    _dataArray = [NSMutableArray array];
    NSString *postUrlString = @"http://api.izhangchu.com/";
    [HTTPMethod getDataByString:postUrlString BodyDic:[changeString changeStringToDictionary:_bodyString] WithDataBlock:^(id data) {
        NSDictionary *dataDic = [data objectForKey:@"data"];
        NSArray *array = [dataDic objectForKey:@"data"];
        for (NSDictionary *dic in array) {
            KSearchSuggestModel *model = [[KSearchSuggestModel alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            [_dataArray addObject:model];
        }
        if (_dataArray.count == 0) {
            UIAlertController *alertController =  [UIAlertController alertControllerWithTitle:@"提示" message:@"没有您要搜索的内容" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
            [alertController addAction:action];
            [self presentViewController:alertController animated:YES completion:nil];
        }
        [_tableView reloadData];
        [_load removeFromSuperview];
    }];
    
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    KSearchSuggestModel *model = [[KSearchSuggestModel alloc]init];
    model = _dataArray[indexPath.row];
    cell.textLabel.text = model.text;
    cell.textLabel.font = [UIFont systemFontOfSize:[FontSize[1] integerValue]];
    //关键字高亮
    NSString *result = [NSString stringWithFormat:@"%@",cell.textLabel.text];
    NSString *keyWord = _searchString;
    NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc]initWithString:result];
    NSRange range = [result rangeOfString:keyWord];
    [attributeString setAttributes:[NSMutableDictionary dictionaryWithObjectsAndKeys:[UIColor colorWithRed:0.19 green:0.75 blue:0.6 alpha:1],NSForegroundColorAttributeName,[UIFont systemFontOfSize:[FontSize[1] integerValue]],NSFontAttributeName, nil] range:range];
    cell.textLabel.attributedText = attributeString;
    return cell;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataArray.count;
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [_searchBar resignFirstResponder];
}
-(void)cancelAction
{
    [_searchBar resignFirstResponder];
}
-(void)viewWillDisappear:(BOOL)animated
{
    [_searchBar removeFromSuperview];
}
//-(void)viewWillAppear:(BOOL)animated
//{
//     self.navigationItem.titleView =  _searchBar;
//}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [_searchBar resignFirstResponder];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
